package core

import (
	"gitee.com/huanminabc/go-utils/common"
	"gitee.com/huanminabc/go-utils/file"
	log "github.com/sirupsen/logrus"
	"os"
)

var ConfigApp ConfigEntity

func init() {
	//应用配置
	userHome, _ := os.UserHomeDir()
	ConfigAppFile = userHome + string(os.PathSeparator) + "go-CodeToolUi-config.json"
	fileOpenFile, err := os.OpenFile(ConfigAppFile, os.O_RDONLY|os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		log.Error("配置文件打开或创建失败")
	}
	defer fileOpenFile.Close()
	//判断内容是否为空
	fileInfo, _ := fileOpenFile.Stat()
	if fileInfo.Size() == 0 {
		json := NewConfigEntity()
		_, err = fileOpenFile.Write([]byte(json))
		if err != nil {
			log.Error("初始化配置失败")
		}
	} else {
		//读取内容
		readFile := file.ReadFile(ConfigAppFile)
		ConfigApp = ConfigEntity{}
		common.JsonToStruct(readFile, &ConfigApp)

	}
}

type ConfigEntity struct {
	DbConfig DbConfigEntity
}
type DbConfigEntity struct {
	MysqlConfig MysqlConfigEntity
}

type MysqlConfigEntity struct {
	Host     string
	Port     string
	User     string
	Password string
}

// 创建一个配置实体,并转换为json字符串
func NewConfigEntity() string {
	configEntity := ConfigEntity{
		DbConfig: DbConfigEntity{
			MysqlConfig: MysqlConfigEntity{},
		},
	}
	json := common.StructToJson(configEntity, true)
	return json
}

// 保存配置
func SaveConfig() {
	json := common.StructToJson(ConfigApp, true)
	file, err := os.OpenFile(ConfigAppFile, os.O_WRONLY, 0666)
	if err != nil {
		log.Error("保存配置失败")
	}
	defer file.Close()
	_, err = file.Write([]byte(json))
	if err != nil {
		log.Error("保存配置失败")
	}
}
